const http = require('http')
const app = require('./module/routes')
const ejs = require('ejs')
const qs = require('querystring')

const { MongoClient } = require('mongodb')
const url = 'mongodb://admin:123456@localhost:27017'; // 权限
const dbName = 'itying'
// const client = new MongoClient(url)

http.createServer(app).listen(8081)

app.static('public') // 修改默认静态web目录

// 配置路由
app.get('/', function(req, res) {
  // res.writeHead(200, {'Content-Type': 'text/html;charset=urf-8'})
  // res.end('home')
  let msg = '数据库里面获取的数据';
  MongoClient.connect(url, (err, client) => {
    client.connect((err) => {
      if(err) {
        console.log(err);
        return;
      }
      const db = client.db(dbName); 
      db.collection('user').find({}).toArray((err, result) => {
        if(err) {
          console.log(err);
          return;
        }
        client.close()
        ejs.renderFile("./views/list.ejs", {
          list: result,
          msg: msg
        }, (err, data) => {
          res.send(data)
        })
      })
    })
  })
})

app.get('/news', function(req, res) {
  res.send('news')
})

app.get('/login', function(req, res) {
  ejs.renderFile('./views/form.ejs', {}, (err, data) => {
    res.send(data)
  })
})

app.post('/login', function(req, res) {
  res.send(req.body)
})

app.get('/register', function(req, res) {
  ejs.renderFile('./views/register.ejs', {}, (err, data) => {
    res.send(data)
  })
})

app.post('/doRegister', function(req, res) {
  // username=zhangsan&password=123
  let body = qs.parse(req.body)

  MongoClient.connect(url, (err, client) => {
    if(err) {
      console.log(err);
      return;
    }
    let db = client.db(dbName)

    db.collection('user').insertOne(body, (err, result) => {
      console.log(result)
      client.close()
      res.send(req.body)
    })
  })

})
